package cn.pro.service;

import cn.pro.api.ILoginService;
import cn.pro.dao.*;
import cn.pro.entity.ProRoleAccess;
import cn.pro.entity.ProUser;
import cn.pro.entity.ProUserRole;
import cn.pro.entity.qo.LoginQo;
import cn.pro.entity.vo.ProAccessVo;
import cn.pro.entity.vo.ProRoleVo;
import cn.pro.entity.vo.ProUserVo;
import cn.pro.utils.EncryptUtil;
import cn.pro.utils.ObjectUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class LoginService implements ILoginService {

    @Autowired
    private ProUserDao proUserDao;

    @Autowired
    private ProUserRoleDao proUserRoleDao;

    @Autowired
    private ProRoleDao proRoleDao;

    @Autowired
    private ProRoleAccessDao proRoleAccessDao;

    @Autowired
    private ProAccessDao proAccessDao;

    @Override
    public Object login(LoginQo loginQo){
        ProUserVo user = proUserDao.selectByName(loginQo.getUserName());
        if (!ObjectUtils.objectCheckIsNull(user)){
            String password = EncryptUtil.getInstance().Base64Decode(user.getPassWord());
            if (password.equals(loginQo.getPassWord())){
                List<ProUserRole> roleUsers = proUserRoleDao.select(user.getId());
                for (ProUserRole proUserRole : roleUsers) {
                    System.out.println(proUserRole.toString());
                    ProRoleVo proRoleVo = proRoleDao.selectById(proUserRole.getRoleId());
                    System.out.println("njcnkas"+proRoleVo.getId());
                    List<ProRoleAccess> proRoleAccesses = proRoleAccessDao.selectByRoleId(proRoleVo.getId());
                    for (ProRoleAccess proRoleAccess: proRoleAccesses) {
                        System.out.println(proRoleAccess.toString());
                        System.out.println(proRoleAccess.getAccessId());
                        ProAccessVo proAccessVo = proAccessDao.selectById(proRoleAccess.getAccessId());
                        proRoleVo.getProAccessVos().add(proAccessVo);
                    }
                    user.getProRoleVos().add(proRoleVo);
                }
                return JSONObject.toJSON(user);
            }
        }
        return "用户不存在！";
    }
}
